//! # Message 类详细单元测试
//!
//! 为 Message、MessageMetadata、MessageAttributes 等相关类型提供完整的单元测试覆盖
//! 确保每个方法、每个参数、每个边界条件都得到测试

use rustcloud_bus::prelude::*;
use rustcloud_bus::message::{
    Message, MessageMetadata, MessageAttributes, MessageType, MessagePriority, PersistenceLevel
};
use serde_json::json;
use chrono::{DateTime, Utc, Duration as ChronoDuration};
use uuid::Uuid;
use std::collections::HashMap;

/// 测试辅助工具
struct MessageTestHelper;

impl MessageTestHelper {
    /// 创建基本测试载荷
    fn create_basic_payload() -> serde_json::Value {
        json!({
            "user_id": 12345,
            "action": "test_action",
            "timestamp": Utc::now().to_rfc3339(),
            "data": {
                "key1": "value1",
                "key2": 42,
                "key3": true
            }
        })
    }

    /// 创建复杂测试载荷
    fn create_complex_payload() -> serde_json::Value {
        json!({
            "nested": {
                "deeply": {
                    "nested": {
                        "value": "deep_value",
                        "array": [1, 2, 3, 4, 5],
                        "object": {
                            "property": "nested_property"
                        }
                    }
                }
            },
            "unicode": "测试中文 🎉 Тест العربية",
            "special_chars": "!@#$%^&*()_+-={}[]|\\:;\"'<>,.?/~`",
            "numbers": {
                "integer": 42,
                "float": 3.14159,
                "negative": -100,
                "zero": 0
            },
            "booleans": {
                "true": true,
                "false": false
            },
            "null_value": null,
            "empty_array": [],
            "empty_object": {}
        })
    }

    /// 创建各种边界情况的载荷
    fn create_edge_case_payloads() -> Vec<serde_json::Value> {
        vec![
            json!(null),                        // null值
            json!(""),                          // 空字符串
            json!(0),                           // 零值
            json!(false),                       // false值
            json!([]),                          // 空数组
            json!({}),                          // 空对象
            json!(i64::MAX),                    // 最大整数
            json!(i64::MIN),                    // 最小整数
            json!("x".repeat(10000)),           // 长字符串
            json!(vec![1; 1000]),               // 大数组
            json!((0..100).map(|i| (format!("key{}", i), i)).collect::<HashMap<String, i32>>()) // 大对象
        ]
    }
}

mod message_creation_tests {
    use super::*;

    /// 测试 Message::new 方法
    #[test]
    fn test_message_new_comprehensive() {
        let payload = MessageTestHelper::create_basic_payload();
        let message = Message::new("test.topic", payload.clone());

        // 验证基本属性
        assert_eq!(message.topic(), "test.topic");
        assert_eq!(message.payload(), &payload);
        assert!(message.id().to_string().len() > 0);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Event);
        assert_eq!(message.metadata().attributes.priority, MessagePriority::Normal);
        
        // 验证时间戳
        let now = Utc::now();
        let created_at = message.metadata().created_at;
        let diff = now.signed_duration_since(created_at);
        assert!(diff.num_seconds().abs() < 5, "创建时间应该接近当前时间");
    }

    /// 测试各种主题格式
    #[test]
    fn test_message_new_with_various_topics() {
        let payload = json!({"test": "data"});
        
        let test_topics = vec![
            "simple",                           // 简单主题
            "domain.service.action",            // 分层主题
            "user.events.created",              // 事件主题
            "user.commands.delete",             // 命令主题
            "系统.事件.创建",                    // 中文主题
            "test-with-dashes",                 // 带连字符
            "test_with_underscores",            // 带下划线
            "test.with.123.numbers",            // 带数字
            "a".repeat(500).as_str(),           // 长主题
            "test.特殊.字符.🎉",                 // 特殊字符
        ];

        for topic in test_topics {
            let message = Message::new(topic, payload.clone());
            assert_eq!(message.topic(), topic);
            assert_eq!(message.payload(), &payload);
        }
    }

    /// 测试各种载荷类型
    #[test]
    fn test_message_new_with_various_payloads() {
        let topic = "test.payload";
        let payloads = MessageTestHelper::create_edge_case_payloads();

        for (i, payload) in payloads.into_iter().enumerate() {
            let message = Message::new(topic, payload.clone());
            assert_eq!(message.topic(), topic);
            assert_eq!(message.payload(), &payload, "载荷 {} 不匹配", i);
        }
    }

    /// 测试复杂载荷
    #[test]
    fn test_message_new_with_complex_payload() {
        let payload = MessageTestHelper::create_complex_payload();
        let message = Message::new("complex.test", payload.clone());

        assert_eq!(message.payload(), &payload);
        
        // 验证可以访问嵌套数据
        assert_eq!(message.payload()["nested"]["deeply"]["nested"]["value"], "deep_value");
        assert_eq!(message.payload()["numbers"]["float"], 3.14159);
        assert_eq!(message.payload()["unicode"], "测试中文 🎉 Тест العربية");
    }
}

mod message_type_creation_tests {
    use super::*;

    /// 测试 Message::event 方法
    #[test]
    fn test_message_event_creation() {
        let payload = json!({"event_data": "test"});
        let message = Message::event("events.test", payload.clone());

        assert_eq!(message.topic(), "events.test");
        assert_eq!(message.payload(), &payload);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Event);
    }

    /// 测试 Message::command 方法
    #[test]
    fn test_message_command_creation() {
        let payload = json!({"command_data": "execute"});
        let message = Message::command("commands.execute", payload.clone());

        assert_eq!(message.topic(), "commands.execute");
        assert_eq!(message.payload(), &payload);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Command);
    }

    /// 测试 Message::query 方法
    #[test]
    fn test_message_query_creation() {
        let payload = json!({"query_params": {"id": 123}});
        let message = Message::query("queries.get_user", payload.clone());

        assert_eq!(message.topic(), "queries.get_user");
        assert_eq!(message.payload(), &payload);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Query);
    }

    /// 测试 Message::notification 方法
    #[test]
    fn test_message_notification_creation() {
        let payload = json!({"notification_text": "Hello!"});
        let message = Message::notification("notifications.alert", payload.clone());

        assert_eq!(message.topic(), "notifications.alert");
        assert_eq!(message.payload(), &payload);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Notification);
    }

    /// 测试 Message::reply 方法
    #[test]
    fn test_message_reply_creation() {
        let payload = json!({"reply_data": "response"});
        let correlation_id = Uuid::new_v4();
        let message = Message::reply("replies.user_query", payload.clone(), correlation_id);

        assert_eq!(message.topic(), "replies.user_query");
        assert_eq!(message.payload(), &payload);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Reply);
        assert_eq!(message.metadata().correlation_id, Some(correlation_id));
    }

    /// 测试所有消息类型与不同载荷的组合
    #[test]
    fn test_all_message_types_with_edge_case_payloads() {
        let payloads = MessageTestHelper::create_edge_case_payloads();
        let message_types = vec![
            ("event", MessageType::Event),
            ("command", MessageType::Command),
            ("query", MessageType::Query),
            ("notification", MessageType::Notification),
            ("reply", MessageType::Reply),
        ];

        for (type_name, expected_type) in message_types {
            for (i, payload) in payloads.iter().enumerate() {
                let topic = format!("{}.test.{}", type_name, i);
                
                let message = match expected_type {
                    MessageType::Event => Message::event(&topic, payload.clone()),
                    MessageType::Command => Message::command(&topic, payload.clone()),
                    MessageType::Query => Message::query(&topic, payload.clone()),
                    MessageType::Notification => Message::notification(&topic, payload.clone()),
                    MessageType::Reply => Message::reply(&topic, payload.clone(), Uuid::new_v4()),
                };

                assert_eq!(message.topic(), topic);
                assert_eq!(message.payload(), payload);
                assert_eq!(message.metadata().attributes.message_type, expected_type);
            }
        }
    }
}

mod message_builder_tests {
    use super::*;

    /// 测试 Message::with_metadata 方法
    #[test]
    fn test_message_with_metadata() {
        let original_message = Message::new("test.topic", json!({"data": "test"}));
        
        let custom_metadata = MessageMetadata::new("custom.topic")
            .with_correlation_id(Uuid::new_v4())
            .with_sender("test_sender".to_string())
            .with_reply_to("reply.topic".to_string())
            .with_priority(MessagePriority::High)
            .with_message_type(MessageType::Command);

        let updated_message = original_message.with_metadata(custom_metadata.clone());

        assert_eq!(updated_message.topic(), "custom.topic");
        assert_eq!(updated_message.metadata().sender, custom_metadata.sender);
        assert_eq!(updated_message.metadata().reply_to, custom_metadata.reply_to);
        assert_eq!(updated_message.metadata().correlation_id, custom_metadata.correlation_id);
        assert_eq!(updated_message.metadata().attributes.priority, MessagePriority::High);
        assert_eq!(updated_message.metadata().attributes.message_type, MessageType::Command);
    }

    /// 测试 MessageBuilder 的使用
    #[test]
    fn test_message_builder_comprehensive() {
        let correlation_id = Uuid::new_v4();
        let message = MessageBuilder::new()
            .topic("builder.test")
            .payload(json!({"builder": "test"}))
            .message_type(MessageType::Command)
            .priority(MessagePriority::High)
            .correlation_id(correlation_id)
            .sender("builder_sender")
            .receiver("builder_receiver")
            .reply_to("builder.reply")
            .build()
            .unwrap();

        assert_eq!(message.topic(), "builder.test");
        assert_eq!(message.metadata().correlation_id, Some(correlation_id));
        assert_eq!(message.metadata().sender, Some("builder_sender".to_string()));
        assert_eq!(message.metadata().receiver, Some("builder_receiver".to_string()));
        assert_eq!(message.metadata().reply_to, Some("builder.reply".to_string()));
        assert_eq!(message.metadata().attributes.priority, MessagePriority::High);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Command);
    }

    /// 测试 MessageBuilder 的错误情况
    #[test]
    fn test_message_builder_errors() {
        // 没有设置主题的构建器应该失败
        let result = MessageBuilder::new()
            .payload(json!({"test": "data"}))
            .build();
        
        assert!(result.is_err());
        
        // 只设置主题的构建器应该成功
        let result = MessageBuilder::new()
            .topic("valid.topic")
            .build();
        
        assert!(result.is_ok());
    }

    /// 测试链式构建（使用 MessageBuilder）
    #[test]
    fn test_message_chaining_builder() {
        let correlation_id = Uuid::new_v4();
        
        let message = MessageBuilder::new()
            .topic("chain.test")
            .payload(json!({"data": "chain_test"}))
            .message_type(MessageType::Event)
            .priority(MessagePriority::Critical)
            .correlation_id(correlation_id)
            .sender("chain_sender")
            .receiver("chain_receiver")
            .reply_to("chain.reply")
            .build()
            .unwrap();

        // 验证所有属性都正确设置
        assert_eq!(message.metadata().correlation_id, Some(correlation_id));
        assert_eq!(message.metadata().sender, Some("chain_sender".to_string()));
        assert_eq!(message.metadata().receiver, Some("chain_receiver".to_string()));
        assert_eq!(message.metadata().reply_to, Some("chain.reply".to_string()));
        assert_eq!(message.metadata().attributes.priority, MessagePriority::Critical);
        assert_eq!(message.metadata().attributes.message_type, MessageType::Event);
    }
}

mod message_accessor_tests {
    use super::*;

    /// 测试 Message::id 方法
    #[test]
    fn test_message_id_accessor() {
        let message = Message::new("test.topic", json!({}));
        let id = message.id();
        
        assert_ne!(id, Uuid::nil());
    }

    /// 测试 Message::message_type 方法（通过 metadata 访问）
    #[test]
    fn test_message_type_accessor() {
        let message_types = vec![
            (Message::event("test", json!({})), MessageType::Event),
            (Message::command("test", json!({})), MessageType::Command),
            (Message::query("test", json!({})), MessageType::Query),
            (Message::notification("test", json!({})), MessageType::Notification),
        ];

        for (message, expected_type) in message_types {
            assert_eq!(message.metadata().attributes.message_type, expected_type);
        }
    }

    /// 测试 Message::priority 方法（通过 metadata 访问）
    #[test]
    fn test_message_priority_accessor() {
        let priorities = vec![
            MessagePriority::Low,
            MessagePriority::Normal,
            MessagePriority::High,
            MessagePriority::Critical,
        ];

        for priority in priorities {
            let mut metadata = MessageMetadata::new("test.topic");
            metadata.attributes.priority = priority;
            let message = Message::new("test.topic", json!({})).with_metadata(metadata);
            assert_eq!(message.metadata().attributes.priority, priority);
        }
    }

    /// 测试 Message::created_at 方法（通过 metadata 访问）
    #[test]
    fn test_message_created_at_accessor() {
        let before = Utc::now();
        let message = Message::new("test.topic", json!({}));
        let after = Utc::now();
        
        let created_at = message.metadata().created_at;
        assert!(created_at >= before && created_at <= after, "创建时间应该在测试时间范围内");
    }

    /// 测试 Message::is_expired 方法（通过 metadata 访问）
    #[test]
    fn test_message_is_expired() {
        // 未设置过期时间的消息不应该过期
        let message_no_expiry = Message::new("test.topic", json!({}));
        assert!(!message_no_expiry.metadata().is_expired(), "没有过期时间的消息不应该过期");

        // 未来过期时间的消息不应该过期
        let future_expiry = Utc::now() + ChronoDuration::hours(1);
        let mut metadata_future = MessageMetadata::new("test.topic");
        metadata_future.attributes.expires_at = Some(future_expiry);
        let message_future = Message::new("test.topic", json!({})).with_metadata(metadata_future);
        assert!(!message_future.metadata().is_expired(), "未来过期的消息不应该过期");

        // 过去过期时间的消息应该过期
        let past_expiry = Utc::now() - ChronoDuration::hours(1);
        let mut metadata_past = MessageMetadata::new("test.topic");
        metadata_past.attributes.expires_at = Some(past_expiry);
        let message_past = Message::new("test.topic", json!({})).with_metadata(metadata_past);
        assert!(message_past.metadata().is_expired(), "过去过期的消息应该过期");
    }

    /// 测试 Message::should_delay 方法（通过 metadata 访问）
    #[test]
    fn test_message_should_delay() {
        // 未设置延迟的消息不应该延迟
        let message_no_delay = Message::new("test.topic", json!({}));
        assert!(!message_no_delay.metadata().should_delay(), "没有延迟时间的消息不应该延迟");

        // 过去延迟时间的消息不应该延迟
        let past_delay = Utc::now() - ChronoDuration::minutes(30);
        let mut metadata_past_delay = MessageMetadata::new("test.topic");
        metadata_past_delay.attributes.delay_until = Some(past_delay);
        let message_past_delay = Message::new("test.topic", json!({})).with_metadata(metadata_past_delay);
        assert!(!message_past_delay.metadata().should_delay(), "过去延迟的消息不应该延迟");

        // 未来延迟时间的消息应该延迟
        let future_delay = Utc::now() + ChronoDuration::minutes(30);
        let mut metadata_future_delay = MessageMetadata::new("test.topic");
        metadata_future_delay.attributes.delay_until = Some(future_delay);
        let message_future_delay = Message::new("test.topic", json!({})).with_metadata(metadata_future_delay);
        assert!(message_future_delay.metadata().should_delay(), "未来延迟的消息应该延迟");
    }
}

mod message_serialization_tests {
    use super::*;

    /// 测试 Message 的 JSON 序列化
    #[test]
    fn test_message_json_serialization() {
        let metadata = MessageMetadata::new("serialize.test")
            .with_correlation_id(Uuid::new_v4())
            .with_sender("test_sender")
            .with_priority(MessagePriority::High);
            
        let message = Message::new("serialize.test", json!({"data": "test"}))
            .with_metadata(metadata);

        // 序列化为 JSON
        let json_str = serde_json::to_string(&message).unwrap();
        assert!(!json_str.is_empty());
        assert!(json_str.contains("serialize.test"));
        assert!(json_str.contains("test_sender"));
        assert!(json_str.contains("High"));

        // 从 JSON 反序列化
        let deserialized: Message = serde_json::from_str(&json_str).unwrap();
        assert_eq!(deserialized.topic(), message.topic());
        assert_eq!(deserialized.payload(), message.payload());
        assert_eq!(deserialized.metadata().sender, message.metadata().sender);
        assert_eq!(deserialized.metadata().attributes.priority, message.metadata().attributes.priority);
    }

    /// 测试复杂载荷的序列化
    #[test]
    fn test_complex_payload_serialization() {
        let complex_payload = MessageTestHelper::create_complex_payload();
        let message = Message::new("complex.serialize", complex_payload.clone());

        let json_str = serde_json::to_string(&message).unwrap();
        let deserialized: Message = serde_json::from_str(&json_str).unwrap();

        assert_eq!(deserialized.payload(), &complex_payload);
        assert_eq!(deserialized.payload()["unicode"], "测试中文 🎉 Тест العربية");
        assert_eq!(deserialized.payload()["nested"]["deeply"]["nested"]["value"], "deep_value");
    }

    /// 测试边界情况的序列化
    #[test]
    fn test_edge_case_serialization() {
        let edge_payloads = MessageTestHelper::create_edge_case_payloads();
        
        for (i, payload) in edge_payloads.into_iter().enumerate() {
            let message = Message::new(&format!("edge.{}", i), payload.clone());
            
            let json_str = serde_json::to_string(&message)
                .expect(&format!("序列化边界情况 {} 失败", i));
            
            let deserialized: Message = serde_json::from_str(&json_str)
                .expect(&format!("反序列化边界情况 {} 失败", i));
            
            assert_eq!(deserialized.payload(), &payload, "边界情况 {} 的载荷不匹配", i);
        }
    }

    /// 测试 MessageMetadata 的序列化
    #[test]
    fn test_metadata_serialization() {
        let correlation_id = Uuid::new_v4();
        let expiry = Utc::now() + ChronoDuration::hours(1);
        
        let metadata = MessageMetadata::new("meta.test")
            .with_correlation_id(correlation_id)
            .with_sender("meta_sender")
            .with_receiver("meta_receiver")
            .with_reply_to("meta.reply")
            .with_priority(MessagePriority::Critical)
            .with_persistence(PersistenceLevel::Replicated)
            .with_expires_at(expiry);

        let json_str = serde_json::to_string(&metadata).unwrap();
        let deserialized: MessageMetadata = serde_json::from_str(&json_str).unwrap();

        assert_eq!(deserialized.topic, metadata.topic);
        assert_eq!(deserialized.correlation_id, metadata.correlation_id);
        assert_eq!(deserialized.sender, metadata.sender);
        assert_eq!(deserialized.receiver, metadata.receiver);
        assert_eq!(deserialized.reply_to, metadata.reply_to);
        assert_eq!(deserialized.attributes.priority, metadata.attributes.priority);
        assert_eq!(deserialized.attributes.persistence, metadata.attributes.persistence);
    }
}

mod message_clone_tests {
    use super::*;

    /// 测试 Message 的克隆
    #[test]
    fn test_message_clone() {
        let metadata = MessageMetadata::new("clone.test")
            .with_correlation_id(Uuid::new_v4())
            .with_sender("original_sender")
            .with_priority(MessagePriority::High);
            
        let original = Message::new("clone.test", json!({"data": "original"}))
            .with_metadata(metadata.clone());

        let cloned = original.clone();

        // 验证克隆后的对象与原对象相等
        assert_eq!(cloned.id(), original.id());
        assert_eq!(cloned.topic(), original.topic());
        assert_eq!(cloned.payload(), original.payload());
        assert_eq!(cloned.metadata().correlation_id, original.metadata().correlation_id);
        assert_eq!(cloned.metadata().sender, original.metadata().sender);
        assert_eq!(cloned.metadata().attributes.priority, original.metadata().attributes.priority);
    }

    /// 测试克隆后修改不影响原对象
    #[test]
    fn test_clone_independence() {
        let original = Message::new("independence.test", json!({"count": 1}));
        let modified_clone = original.clone();
        
        // 创建一个修改过的元数据
        let mut modified_metadata = modified_clone.metadata().clone();
        modified_metadata = modified_metadata.with_sender("modified_sender")
            .with_priority(MessagePriority::Critical);
        let modified = modified_clone.with_metadata(modified_metadata);

        // 原对象不应该受影响
        assert_ne!(modified.metadata().sender, original.metadata().sender);
        assert_ne!(modified.metadata().attributes.priority, original.metadata().attributes.priority);
        assert_eq!(original.metadata().sender, None);
        assert_eq!(original.metadata().attributes.priority, MessagePriority::Normal);
    }

    /// 测试复杂载荷的克隆
    #[test]
    fn test_complex_payload_clone() {
        let complex_payload = MessageTestHelper::create_complex_payload();
        let original = Message::new("complex.clone", complex_payload.clone());
        let cloned = original.clone();

        assert_eq!(cloned.payload(), original.payload());
        
        // 验证深层嵌套数据的克隆
        assert_eq!(
            cloned.payload()["nested"]["deeply"]["nested"]["value"],
            original.payload()["nested"]["deeply"]["nested"]["value"]
        );
    }
}

mod message_display_tests {
    use super::*;

    /// 测试 Message 的 Display 实现
    #[test]
    fn test_message_display() {
        let metadata = MessageMetadata::new("display.test")
            .with_sender("display_sender");
        let message = Message::new("display.test", json!({"key": "value"}))
            .with_metadata(metadata);

        let display_str = format!("{:?}", message);
        
        // Display 输出应该包含关键信息
        assert!(display_str.contains("display.test"));
        assert!(display_str.contains("display_sender"));
        assert!(display_str.len() > 0);
    }

    /// 测试 Message 的 Debug 实现
    #[test]
    fn test_message_debug() {
        let metadata = MessageMetadata::new("debug.test")
            .with_correlation_id(Uuid::new_v4());
        let message = Message::new("debug.test", json!({"debug": true}))
            .with_metadata(metadata);

        let debug_str = format!("{:?}", message);
        
        // Debug 输出应该包含更详细的信息
        assert!(debug_str.contains("debug.test"));
        assert!(debug_str.contains("debug"));
        assert!(debug_str.len() > 0);
    }
}

mod message_equality_tests {
    use super::*;

    /// 测试 Message 的相等性
    #[test]
    fn test_message_equality() {
        let payload = json!({"test": "equality"});
        let message1 = Message::new("equality.test", payload.clone());
        let message2 = Message::new("equality.test", payload.clone());

        // 不同的消息实例应该不相等（因为有不同的 ID）
        assert_ne!(message1.id(), message2.id());
        
        // 验证主题和载荷相同
        assert_eq!(message1.topic(), message2.topic());
        assert_eq!(message1.payload(), message2.payload());

        // 克隆的消息应该相等
        let cloned = message1.clone();
        assert_eq!(message1.id(), cloned.id());
        assert_eq!(message1.topic(), cloned.topic());
        assert_eq!(message1.payload(), cloned.payload());
    }

    /// 测试不同属性的消息不相等
    #[test]
    fn test_message_inequality() {
        let payload = json!({"test": "inequality"});
        let base_message = Message::new("inequality.test", payload.clone());
        
        // 不同主题
        let different_topic = Message::new("different.topic", payload.clone());
        assert_ne!(base_message.topic(), different_topic.topic());
        
        // 不同载荷
        let different_payload = Message::new("inequality.test", json!({"different": "payload"}));
        assert_ne!(base_message.payload(), different_payload.payload());
        
        // 不同发送者
        let mut different_metadata = base_message.metadata().clone();
        different_metadata = different_metadata.with_sender("different_sender");
        let different_sender = base_message.clone().with_metadata(different_metadata);
        assert_ne!(base_message.metadata().sender, different_sender.metadata().sender);
    }
}

mod message_validation_tests {
    use super::*;

    /// 测试消息验证
    #[test]
    fn test_message_validation() {
        // 正常消息应该通过验证
        let valid_message = Message::new("valid.topic", json!({"data": "valid"}));
        assert!(valid_message.validate().is_ok());
        
        // 空主题应该验证失败
        let mut invalid_message = Message::new("invalid.topic", json!({}));
        invalid_message.metadata.topic = String::new();
        assert!(invalid_message.validate().is_err());
    }

    /// 测试过期验证
    #[test]
    fn test_expiry_validation() {
        let past_time = Utc::now() - ChronoDuration::hours(1);
        let expired_metadata = MessageMetadata::new("expired.test")
            .with_expires_at(past_time);
        let expired_message = Message::new("expired.test", json!({}))
            .with_metadata(expired_metadata);
        
        assert!(expired_message.metadata().is_expired());
        
        let future_time = Utc::now() + ChronoDuration::hours(1);
        let valid_metadata = MessageMetadata::new("valid.test")
            .with_expires_at(future_time);
        let valid_message = Message::new("valid.test", json!({}))
            .with_metadata(valid_metadata);
        
        assert!(!valid_message.metadata().is_expired());
    }

    /// 测试重试次数验证
    #[test]
    fn test_retry_validation() {
        let message = Message::new("retry.test", json!({}));
        
        // 初始重试次数应该为 0
        assert_eq!(message.metadata().attributes.retry_count, 0);
        assert_eq!(message.metadata().attributes.max_retries, 3);
        
        // 测试重试次数是否超过最大值
        assert!(message.metadata().can_retry());
        
        // 设置超过最大重试次数
        let mut metadata_over_retry = message.metadata().clone();
        metadata_over_retry.attributes.retry_count = 5;
        let over_retry_message = message.with_metadata(metadata_over_retry);
        assert!(!over_retry_message.metadata().can_retry());
    }
}